package cn.kailangtu.serialport;

import android.content.Context;
import android.view.Gravity;
import android.widget.TextView;
import android.widget.Toast;

import java.math.BigInteger;

/**
 * Description: 工具类
 */

public class CommonUtils {


    public static final int DEVICE_825 = 0;
    public static final int DEVICE_NEW_825 = 1;
    private static Toast toast;
    public static int deviceType = 0;

    public static void showSingleToast(Context context, String msg) {

        if (toast == null) {
            toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
        } else {
            toast.setText(msg);
        }
        TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
        v.setTextSize(26);
        v.setGravity(Gravity.CENTER);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public static String formatHexString(String hexString) {
        if (hexString.length() % 2 != 0) {
            hexString = "0" + hexString;
        }

        if (hexString.length() < 4) {
            hexString = "00" + hexString;
        }
        return hexString;
    }

    /**
     * 16进制字符串转2进制
     *
     * @param s
     * @return
     */
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
                    .digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    /**
     * 二进制转16进制字符串
     *
     * @param b
     * @return
     */
    public static String ByteArrayToHexString(byte[] b) {
        String a = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }

            a = a + hex;
        }

        return a;
    }






    public static byte[] ArrayAppend(byte[] paramArrayOfByte1,
                                     byte[] paramArrayOfByte2, int paramInt) {
        byte[] arrayOfByte;
        if ((paramArrayOfByte1 == null) && (paramArrayOfByte2 == null)) {
            arrayOfByte = null;
            return arrayOfByte;
        }
        if (paramArrayOfByte1 == null) {
            arrayOfByte = new byte[paramInt];
            System.arraycopy(paramArrayOfByte2, 0, arrayOfByte, 0, paramInt);
            return arrayOfByte;
        }
        if (paramArrayOfByte2 == null) {
            arrayOfByte = new byte[paramArrayOfByte1.length];
            System.arraycopy(paramArrayOfByte1, 0, arrayOfByte, 0,
                    paramArrayOfByte1.length);
            return arrayOfByte;
        }
        arrayOfByte = new byte[paramInt + paramArrayOfByte1.length];
        System.arraycopy(paramArrayOfByte1, 0, arrayOfByte, 0,
                paramArrayOfByte1.length);
        System.arraycopy(paramArrayOfByte2, 0, arrayOfByte,
                paramArrayOfByte1.length, paramInt);
        return arrayOfByte;
    }

    /**
     * 把指令格式的ascii码解析成字符
     *
     * @param string
     * @return
     */
    public static String decodeForAscii(String string) {
        StringBuffer sb = new StringBuffer();
        byte[] array = CommonUtils.hexStringToByteArray(string);
        for (int i = 0; i < array.length; i++) {
            char c = (char) array[i];
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * 将字节数组转换为整型~
     *
     * @return
     */
    //byte 数组与 int 的相互转换
    public static int byteArrayToInt(byte[] b) {
        return b[3] & 0xFF |
                (b[2] & 0xFF) << 8 |
                (b[1] & 0xFF) << 16 |
                (b[0] & 0xFF) << 24;
    }

    public static int byteArrayToInt16(byte[] b) {
        return b[1] & 0xFF |
                (b[0] & 0xFF) << 8;
    }

    public static int byteArrayToInt16(byte h,byte l) {
        return l & 0xFF |
                (h & 0xFF) << 8;
    }

    public static int byteBitToInt(int source,int displacement)
    {
        return (source >> displacement) & 3;
    }
    /**
     * 将浮点数转换字符串，~
     *displacement 小数点后几位
     * @return
     */
    public static String  floatToString(float source,int displacement)
    {
        String data1="";
        if(displacement==0){
            data1="%.0f";
        }else if(displacement==1){
            data1="%.1f";
        }else if(displacement==2){
            data1="%.2f";
        }else if(displacement==3){
            data1="%.3f";
        } else if(displacement==4){
        data1="%.4f";
    }
        return  String.format(data1, source);
    }


    //合并成int
    public static int combineBytesToInt(byte byte1, byte byte2) {
        // 将byte1左移8位，空出的低位由byte2填充
        return (byte1 << 8) | (byte2 & 0xFF);
    }
    //合并成int 无符号数
    public static int bytesToUnsignedInt(byte high, byte low) {
        return ((high & 0xFF) << 8) | (low & 0xFF);
    }




//     * CRC-16 (Modbus) ：
//            * 计算产生校验码
//     * @param data 需要校验的数据
//     * @return 校验码
//     */
    public static String Make_CRC(byte[] data) {
        byte[] buf = new byte[data.length];// 存储需要产生校验码的数据
        for (int i = 0; i < data.length; i++) {
            buf[i] = data[i];
        }
        int len = buf.length;
        int crc = 0xFFFF;//16位
        for (int pos = 0; pos < len; pos++) {
            if (buf[pos] < 0) {
                crc ^= (int) buf[pos] + 256; // XOR byte into least sig. byte of
                // crc
            } else {
                crc ^= (int) buf[pos]; // XOR byte into least sig. byte of crc
            }
            for (int i = 8; i != 0; i--) { // Loop over each bit
                if ((crc & 0x0001) != 0) { // If the LSB is set
                    crc >>= 1; // Shift right and XOR 0xA001
                    crc ^= 0xA001;
                } else
                    // Else LSB is not set
                    crc >>= 1; // Just shift right
            }
        }
        String c = Integer.toHexString(crc);
        if (c.length() == 4) {
            c = c.substring(2, 4) + c.substring(0, 2);
        } else if (c.length() == 3) {
            c = "0" + c;
            c = c.substring(2, 4) + c.substring(0, 2);
        } else if (c.length() == 2) {
            c = "0" + c.substring(1, 2) + "0" + c.substring(0, 1);
        }
        return c;
    }



    public static byte[] int2ByteArray(int a) {
        return new byte[]{
                (byte) ((a >> 8) & 0xFF),
                (byte) (a & 0xFF)
        };
    }


    public static byte[] int1ByteArray(int a) {
        return new byte[]{
                (byte) (a & 0xFF)
        };
    }


    public static int hexToInt(String hex) {
        BigInteger bi = new BigInteger(hex, 16);
        int no = bi.intValue();
        return no;
    }

    public static String getCheckValue(String cmdSource){
        String cmd = cmdSource.substring(0,cmdSource.length());
        String checkString = "";
        if (cmd.length() % 2 == 0) {
//            AppStaticMethods.kLog(TAG + "计算校验的字符串合法：" + cmd);
            int noCount = 0;
            for (int i = 0; i < cmd.length() / 2; i++) {
                String str = cmd.substring(i * 2, (i + 1) * 2);
                int noValue = CommonUtils.hexToInt(str);
                noCount += noValue;
            }
            checkString = Integer.toHexString(noCount);
//            AppStaticMethods.kLog(TAG + "校验：" + str校验);
            checkString = checkString.substring(checkString.length() - 2, checkString.length());
            checkString = checkString.toUpperCase();
        }
        return checkString;
    }

    public static boolean check(String cmdSource){

        String cmd = cmdSource.substring(0,cmdSource.length()-2);
        String checkSource = cmdSource.substring(cmdSource.length()-2).toUpperCase();
        String computeCheck = getCheckValue(cmd);
        return checkSource.equals(computeCheck);
    }

}
